package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.modular.entity.Frameitem;
import cn.stylefeng.guns.modular.entity.Schedule;
import cn.stylefeng.guns.modular.entity.Scheduleitem;
import cn.stylefeng.guns.modular.model.ScheduleitemDto;
import cn.stylefeng.guns.modular.service.FrameitemService;
import cn.stylefeng.guns.modular.service.ScheduleIndexService;
import cn.stylefeng.guns.modular.service.ScheduleitemService;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * 日程项控制
 *
 * @author third_e
 * @create 2019/12/23 0023-下午 4:08
 */

@Controller
@RequestMapping("/scheduleitem")
public class ScheduleitemController extends BaseController {

    private static String PREFIX = "/scheduleitem";

    @Autowired
    public ScheduleIndexService scheduleIndexService;
    @Autowired
    public ScheduleitemService scheduleitemService;
    @Autowired
    public FrameitemService frameitemService;


    /**
     * 跳转到添加日程项界面
     * @param scheduleitemDto
     * 必要参数：scheduleitemDay
     *           frameId
     *           scheduleId
     * @return
     */
    @RequestMapping("/add")
    public String add(ScheduleitemDto scheduleitemDto){
        System.out.println(scheduleitemDto);
        return this.PREFIX +"/scheduleitem_add.html";
    }

    /**
     * 跳转到修改日程项界面
     * @param scheduleitemDto
     * 必要参数：scheduleitemId
     *           frameId
     *           scheduleId
     * @return
     */
    @RequestMapping("/edit")
    public String edit(ScheduleitemDto scheduleitemDto){
        return this.PREFIX +"/scheduleitem_edit.html";
    }


    /**
     * 添加日程项
     * @param scheduleitem
     * @return
     */
    @RequestMapping("/scheduleitem_add")
    @ResponseBody
    public ResponseData scheduleitemAdd(Scheduleitem scheduleitem,String scheduleitemEndDay){
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//时间判断

        Calendar calendar = Calendar.getInstance();
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取日程的信息
        Schedule theschedule = this.scheduleIndexService.getById(scheduleitem.getScheduleId());
        //获取框架项的信息
        Frameitem theframeitem = this.frameitemService.getById(scheduleitem.getFrameitemId());
        //判断当前用户是否具有该日程的添加权限
        if (!user.getId().equals(theschedule.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        //判断日期是否超出日程时间提示时间错误
        try {
            //判断日期是否符合日程的日期范围
            if (sdf.parse(scheduleitem.getScheduleitemDay()).getTime()<sdf.parse(theschedule.getStartData()).getTime() ||
                    sdf.parse(scheduleitem.getScheduleitemDay()).getTime()>sdf.parse(theschedule.getEndData()).getTime()){
                throw new ServiceException(BizExceptionEnum.TIME_ERROR_ITEM);
//                return ResponseData.error(400,"添加失败","日期范围超出日程的范围");
            }
            //判断日程范围是否为空，空则判断日程项是否冲突，
            if (ToolUtil.isEmpty(scheduleitemEndDay) || sdf.parse(scheduleitem.getScheduleitemDay()).getTime() == sdf.parse(scheduleitemEndDay).getTime()){
                //查询对应日程项
                Scheduleitem isDayscheduleitem = this.scheduleitemService.getByDayAndFrameitemId(scheduleitem.getScheduleitemDay(),scheduleitem.getScheduleId(),scheduleitem.getFrameitemId());
                if (ToolUtil.isEmpty(isDayscheduleitem)){//如果为空则表示没有相同日程项，可以插入
                    //补充内容
                    scheduleitem.setFrameId(theschedule.getFrameId());
                    scheduleitem.setEndTime(theframeitem.getEndTime());
                    scheduleitem.setStartTime(theframeitem.getStartTime());
                    //保存
                    this.scheduleitemService.save(scheduleitem);
                    return SUCCESS_TIP;
                }else {
                    throw new ServiceException(BizExceptionEnum.SAME_SCHEDULEITEM);
                }
            } else if (sdf.parse(scheduleitemEndDay).getTime()<sdf.parse(theschedule.getStartData()).getTime() ||
                    sdf.parse(scheduleitemEndDay).getTime()>sdf.parse(theschedule.getEndData()).getTime()){
                throw new ServiceException(BizExceptionEnum.TIME_ERROR_ITEM);
            } else {
                //时间范围符合日程范围则遍历存储
                //获取开始日期和结束日期
                int dayNum;//获取循环次数
                String minDay = ""; //获取最小日期
                List<String> conflictDay = new ArrayList<>();
                if (sdf.parse(scheduleitem.getScheduleitemDay()).getTime() <sdf.parse(scheduleitemEndDay).getTime()){
                    dayNum = (int) ((sdf.parse(scheduleitemEndDay).getTime() - sdf.parse(scheduleitem.getScheduleitemDay()).getTime())/(1000*24*60*60)+1);
                    minDay = scheduleitem.getScheduleitemDay();
                }else {
                    dayNum = (int) ((sdf.parse(scheduleitem.getScheduleitemDay()).getTime() - sdf.parse(scheduleitemEndDay).getTime())/(1000*24*60*60)+1);
                    minDay = scheduleitemEndDay;
                }
                Date dd = sdf.parse(minDay);
                calendar.setTime(dd);
                for (int i =0;i<dayNum;i++){
                    System.out.println("选择的日期"+scheduleitem.getScheduleitemDay()+"选择的范围日期"+scheduleitemEndDay);
                    System.out.println("\n\n\n当前日期为"+sdf.format(calendar.getTime()));
                    //查询对应日程项
                    Scheduleitem isDayscheduleitem = this.scheduleitemService.getByDayAndFrameitemId(sdf.format(calendar.getTime()),scheduleitem.getScheduleId(),scheduleitem.getFrameitemId());
                    if (ToolUtil.isEmpty(isDayscheduleitem)) {//如果为空则表示没有相同日程项，可以插入
                        //补充内容
                        scheduleitem.setScheduleitemId(null);
                        scheduleitem.setScheduleitemDay(sdf.format(calendar.getTime()));
                        scheduleitem.setFrameId(theschedule.getFrameId());
                        scheduleitem.setEndTime(theframeitem.getEndTime());
                        scheduleitem.setStartTime(theframeitem.getStartTime());
                        //保存
                        this.scheduleitemService.save(scheduleitem);

                    }else { //有行程冲突则存储下来时间提示对应行程冲突
                        conflictDay.add(sdf.format(calendar.getTime()));
                    }
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                if (conflictDay.size()!=0){
                    return ResponseData.error(400,"部分日期添加失败",conflictDay);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


//        //补充内容
//        scheduleitem.setFrameId(theschedule.getFrameId());
//        scheduleitem.setEndTime(theframeitem.getEndTime());
//        scheduleitem.setStartTime(theframeitem.getStartTime());
//        //保存
//        this.scheduleitemService.save(scheduleitem);
        return SUCCESS_TIP;
    }

    /**
     * 获取一个日程项信息
     * @param scheduleitemId
     * @return
     */
    @RequestMapping("getOnescheduleitemInfo")
    @ResponseBody
    public ResponseData getOnescheduleitemInfo(Long scheduleitemId){
        //判断请求是否有误
        if (ToolUtil.isEmpty(scheduleitemId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Scheduleitem scheduleitem = this.scheduleitemService.getById(scheduleitemId);
        return ResponseData.success(scheduleitem);
    }

    /**
     * 修改日程项信息
     * @param scheduleitem
     * @return
     */
    @RequestMapping("scheduleitem_edit")
    @ResponseBody
    public ResponseData scheduleitemEdit(Scheduleitem scheduleitem){
        //判断请求是否有误
        if (ToolUtil.isEmpty(scheduleitem.getScheduleitemId())){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取日程的信息
        Schedule theschedule = this.scheduleIndexService.getById(scheduleitem.getScheduleId());
        //判断当前用户是否具有该日程的添加权限
        if (!user.getId().equals(theschedule.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        //获取日程项的信息
        Scheduleitem thescheduleitem = this.scheduleitemService.getById(scheduleitem.getScheduleitemId());
        //获取新的框架项信息
        Frameitem newframeitem = this.frameitemService.getById(scheduleitem.getFrameitemId());

        //补充内容
        scheduleitem.setStartTime(newframeitem.getStartTime());
        scheduleitem.setEndTime(newframeitem.getEndTime());
        scheduleitem.setScheduleId(theschedule.getScheduleId());
        scheduleitem.setFrameId(theschedule.getFrameId());

        //修改日程项信息
        this.scheduleitemService.updateById(scheduleitem);
        return SUCCESS_TIP;
    }

    /**
     * 删除日程项
     * @param scheduleitemId
     * @param scheduleId
     * @return
     */
    @RequestMapping("scheduleitem_delete")
    @ResponseBody
    public ResponseData scheduleitemDelete(Long scheduleitemId,Long scheduleId){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取日程的信息
        Schedule theschedule = this.scheduleIndexService.getById(scheduleId);
        //判断当前用户是否具有该日程的添加权限
        if (!user.getId().equals(theschedule.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        //删除日程项信息
        this.scheduleitemService.deleteScheduleitemById(scheduleitemId);
        return SUCCESS_TIP;
    }


    /**
     * 获取对应日程及所有日程项
     * @param scheduleId
     * @return
     */
    @RequestMapping("/scheduleitem_list")
    @ResponseBody
    public ResponseData scheduleitemAll(@RequestParam Long scheduleId){

        //判断当前请求是否有误
        if (ToolUtil.isEmpty(scheduleId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();

        //获取当前日程所有的日程项
        Collection<Scheduleitem> scheduleitems = this.scheduleitemService.selectByscheduleId(scheduleId);

        return ResponseData.success(scheduleitems);
    }




}
